﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

struct MessageStruct
{
    public MessageStruct(string mes, Vector4 color)
    {
        m_Message = mes;
        m_Color = color;
    }
    public string m_Message;
    public Vector4 m_Color;
}
class MessageShow
{
    public static MessageShow Instance = new MessageShow();

    public CallbackString OnMessageCallback;

    public List<MessageStruct> m_ShowMessageList = new List<MessageStruct>();
    float m_TimeCount = 0;

    Canvas m_Cancas;
    bool isInited = false;
    public void Init()
    {
        if (isInited)
            return;
        isInited = true;
        GameObject obj = new GameObject();
        obj.name = "MessageShowCanvas";
        m_Cancas = obj.AddComponent<Canvas>();
        m_Cancas.renderMode = RenderMode.ScreenSpaceOverlay;
        m_Cancas.sortingOrder = 100;
        GameObject.DontDestroyOnLoad(m_Cancas);
    }

    public void Update()
    {
        float timeMax = 0.4f;
        m_TimeCount += Time.deltaTime;
        if (m_ShowMessageList.Count > 0 && m_TimeCount > timeMax)
        {
            MessageStruct mstr = m_ShowMessageList[0];
            Messaage(mstr.m_Message, mstr.m_Color);
            m_ShowMessageList.Remove(mstr);
            m_TimeCount = 0;
        }
        if (Input.GetKeyDown(KeyCode.Y))
        {
            Message("啊啊啊，testtestTR   Tetst， 啊啊啊");
        }
    }

    /// <summary>
    ///     显示一个提示信息，在屏幕中央
    /// </summary>
    /// <param name="message"></param>
    public void Message(string message)
    {
        Messaage(message, Vector4.one);
    }
    public void Error(string message)
    {
        Messaage(message, Vector4.one);
        UnityEngine.Debug.LogError(message);
    }
    public void Messaage(string message, Vector4 color, bool append = false)
    {
        if (append)
        {
            m_ShowMessageList.Add(new MessageStruct(message, color));
            return;
        }
        if (m_Cancas)
        {
            GameObject obj = new GameObject();
            var outline = obj.AddComponent<Outline>();
            outline.effectDistance = new Vector2(2, 2);
            obj.transform.SetParent(m_Cancas.transform);
            obj.transform.localScale = Vector3.one;

            RectTransform rect = obj.AddComponent<RectTransform>();
            rect.sizeDelta = new Vector2(Screen.width, 50);
            rect.localScale = new Vector3(1, 1, 1);
            Text text = obj.AddComponent<Text>();
            text.font = Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");
            text.fontSize = 24;
            text.fontStyle = FontStyle.Bold;
            text.alignment = TextAnchor.MiddleCenter;
            text.raycastTarget = false;
            text.color = color;
            Message message2 = obj.AddComponent<Message>();

            message2.Text = message;
        }
        if (OnMessageCallback != null)
            OnMessageCallback(message);
    }
}